import {createRouter, createWebHistory} from 'vue-router'
import {useUserStore} from '@/shared/user.ts'
import {ElMessage} from 'element-plus'

// 导入模块化路由
import { DocRoutes } from '@/modules/doc'
import { NavbarRoutes } from '@/modules/navbar'
import { FileRoutes } from '@/modules/file'
import { routes as DevToolsRoutes } from '@/modules/dev-tools'
import { TodoRoutes } from '@/modules/todo'
import { MomentsRoutes } from '@/modules/moments'
import { JournalRoutes } from '@/modules/journal'
import collectRoutes from '@/modules/collect/routes'

const routes = [
    {
        path: '/',
        redirect: '/apps'
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: {
            title: '用户登录',
            requiresAuth: false
        }
    },
    {
        path: '/apps',
        name: 'Apps',
        component: () => import('@/views/Home.vue'),
        meta: {
            title: '应用首页',
            requiresAuth: false
        }
    },
    // 模块化路由
    DocRoutes,
    NavbarRoutes,
    TodoRoutes,
    MomentsRoutes,
    JournalRoutes,
    ...FileRoutes,
    ...DevToolsRoutes,
    ...collectRoutes
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, _from, next) => {
    const userStore = useUserStore()

    // 确保用户状态已初始化
    userStore.initUserState()

    // 设置页面标题
    if (to.meta?.title) {
        document.title = `${to.meta.title} - 懒熊文档`
    }

    // 检查是否需要登录
    if (to.meta?.requiresAuth) {
        if (!userStore.isLoggedIn) {
            ElMessage.warning('请先登录以访问此功能')
            // 保存当前要访问的路径，登录后跳转回来
            next({
                path: '/login',
                query: {redirect: to.fullPath}
            })
            return
        }
    }

    // 如果已登录且访问登录页，直接跳转到首页
    if (to.path === '/login' && userStore.isLoggedIn) {
        next('/apps')
        return
    }

    next()
})

export default router